const questionService = require('../services/questionService');

const questionController = {
  // 获取所有问题
  async getAllQuestions(ctx) {
    try {
      const questions = questionService.getAllQuestions();
      ctx.status = 200;
      ctx.body = {
        status: 'success',
        message: '获取所有问题成功',
        data: questions
      };
    } catch (err) {
      ctx.status = 400;
      ctx.body = {
        status: 'error',
        message: '获取所有问题失败',
        error: err.message
      };
    }
  },

  // 根据维度获取问题
  async getQuestionsByDimension(ctx) {
    try {
      const { dimension } = ctx.params;
      if (!dimension) {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: '参数错误',
          error: '维度不能为空'
        };
        return;
      }
      
      const questions = questionService.getQuestionsByDimension(dimension);
      ctx.status = 200;
      ctx.body = {
        status: 'success',
        message: `获取${dimension}维度问题成功`,
        data: questions
      };
    } catch (err) {
      ctx.status = 400;
      ctx.body = {
        status: 'error',
        message: '获取问题失败',
        error: err.message
      };
    }
  },

  // 获取所有维度
  async getAllDimensions(ctx) {
    try {
      const dimensions = questionService.getAllDimensions();
      ctx.status = 200;
      ctx.body = {
        status: 'success',
        message: '获取所有维度成功',
        data: dimensions
      };
    } catch (err) {
      ctx.status = 400;
      ctx.body = {
        status: 'error',
        message: '获取维度失败',
        error: err.message
      };
    }
  },

  // 根据问题ID获取单个问题
  async getQuestionById(ctx) {
    try {
      const { id } = ctx.params;
      if (!id) {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: '参数错误',
          error: '问题ID不能为空'
        };
        return;
      }
      
      const questionId = parseInt(id);
      if (isNaN(questionId)) {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: '参数错误',
          error: '问题ID必须是数字'
        };
        return;
      }
      
      const question = questionService.getQuestionById(questionId);
      if (!question) {
        ctx.status = 404;
        ctx.body = {
          status: 'error',
          message: '获取问题失败',
          error: '问题不存在'
        };
        return;
      }
      
      ctx.status = 200;
      ctx.body = {
        status: 'success',
        message: '获取问题成功',
        data: question
      };
    } catch (err) {
      ctx.status = 400;
      ctx.body = {
        status: 'error',
        message: '获取问题失败',
        error: err.message
      };
    }
  },

  // 提交测评答案并获取结果
  async submitAssessment(ctx) {
    try {
      const { answers, assessmentId } = ctx.request.body;
      
      if (!answers || typeof answers !== 'object') {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: '参数错误',
          error: '答案格式不正确'
        };
        return;
      }
      
      if (!assessmentId) {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: '参数错误',
          error: '测评ID不能为空'
        };
        return;
      }
      
      // 验证答案
      try {
        questionService.validateAnswers(answers);
      } catch (validationError) {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: '答案验证失败',
          error: validationError.message
        };
        return;
      }
      
      // 计算得分
      const scores = questionService.calculateScores(answers);
      
      // 生成测评报告
      const report = questionService.generateReport(scores);
      
      // 返回结果
      ctx.status = 200;
      ctx.body = {
        status: 'success',
        message: '测评提交成功',
        data: {
          scores: scores,
          report: report,
          assessmentId: assessmentId,
          resultId: Date.now() // 生成一个临时的resultId
        }
      };
    } catch (err) {
      ctx.status = 400;
      ctx.body = {
        status: 'error',
        message: '测评提交失败',
        error: err.message
      };
    }
  },

  // 批量获取问题 - 已从路由中移除，仅供参考
  async getQuestionsInBatch(ctx) {
    try {
      const { questionIds } = ctx.query;
      
      if (!questionIds) {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: '参数错误',
          error: '问题ID列表不能为空'
        };
        return;
      }
      
      // 解析问题ID列表
      const ids = questionIds.split(',').map(id => parseInt(id)).filter(id => !isNaN(id));
      
      if (ids.length === 0) {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: '参数错误',
          error: '无效的问题ID列表'
        };
        return;
      }
      
      // 获取问题
      const questions = [];
      for (const id of ids) {
        const question = questionService.getQuestionById(id);
        if (question) {
          questions.push(question);
        }
      }
      
      ctx.status = 200;
      ctx.body = {
        status: 'success',
        message: '批量获取问题成功',
        data: questions
      };
    } catch (err) {
      ctx.status = 400;
      ctx.body = {
        status: 'error',
        message: '批量获取问题失败',
        error: err.message
      };
    }
  },

  // 获取题库统计信息
  async getQuestionBankStats(ctx) {
    try {
      const questions = questionService.getAllQuestions();
      const dimensions = questionService.getAllDimensions();
      
      // 按维度统计问题数量
      const questionsByDimension = {};
      dimensions.forEach(dimension => {
        questionsByDimension[dimension] = questions.filter(q => q.dimension === dimension).length;
      });
      
      const stats = {
        totalQuestions: questions.length,
        totalDimensions: dimensions.length,
        questionsByDimension: questionsByDimension
      };
      
      ctx.body = success('获取题库统计信息成功', stats);
    } catch (err) {
      ctx.body = error('获取题库统计信息失败', err.message);
    }
  },

  // 根据测评ID获取问题
  async getQuestionsByAssessmentId(ctx) {
    try {
      const { id } = ctx.params;
      if (!id) {
        ctx.status = 400;
        ctx.body = {
          status: 'error',
          message: '参数错误',
          error: '测评ID不能为空'
        };
        return;
      }
      
      // 根据测评ID重置题库
      questionService.resetQuestionBank(id);
      
      // 获取所有问题
      const questions = questionService.getAllQuestions();
      
      ctx.status = 200;
      ctx.body = questions;
    } catch (err) {
      ctx.status = 400;
      ctx.body = {
        status: 'error',
        message: '获取测评问题失败',
        error: err.message
      };
    }
  }
};

module.exports = questionController;